package cc.lucien.service;

import cc.lucien.dao.UserDao;
import cc.lucien.utils.DBHelper;

import javax.servlet.http.Part;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

public class RegisterService {
    public String register(String username, String password1, String password2, String realname,
                           Part part, String email, Long phone, String source) {
        //对密码的一致性进行校验
        if (!password1.equals(password2))
            return "Passwords does not match!";
        //对图片的格式进行校验
        if (part != null){
            String type = part.getContentType();
            if (!type.equalsIgnoreCase("image/png") && !type.equalsIgnoreCase("image/jpeg")
            && !type.equalsIgnoreCase("image/jpg"))
                return "Image format error";
        }
        //查看数据库是否已存在该用户名
        UserDao userDao = new UserDao();
        String result = "";
        ResultSet resultSet = userDao.findByUsername(username);
        try {
            while (resultSet.next())
                result = resultSet.getString("username");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBHelper.close();
        }
        if (result.equals(username))
            return "The user name already exists";

        //通过以上校验，说明是合法的，可以注册。

        //存储用户头像,并获得文件路径
        String imgUrl = savaImg(username, part);
        Object[] objects = {
                username,password1,realname,imgUrl,email,phone,source
        };
        int resultInt = userDao.add(objects);
        if (resultInt < 0)
            return "unknown error";
        return "success";
    }

    private String savaImg(String username, Part part) {
        String fileName = username + "." + part.getContentType().split("/")[1];
        String path = "F:\\photo\\" + fileName;
        //写文件
        try {
            part.write(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }
}
